//
//  TCAirportModel.m
//  EFBTerminalCharts
//
//  Created by xiu-imac on 13-11-1.
//  Copyright (c) 2013年 adcc. All rights reserved.
//

#import "TCAirportModel.h"
#import "FMDatabase.h"
#import <ChartContext.h>
#import "ChartFileHelper.h"


#define AIRPORTTABLE             @"t_airport"
#define CHARTTABLE               @"t_chart"
#define CHARTTYPETABLE           @"t_chart_type"
#define DOCTABLE                 @"t_doc"

@interface TCAirportModel()
@end

//加“航班设置”配置项，独立配置任务机场
static NSArray *airportArray;
static NSMutableArray *taskAirportArray;
static NSMutableDictionary *favorateDic;
static NSString *airportICAO;
static NSString *typeName;
static NSMutableDictionary *rotateDic;
static NSMutableDictionary *selectedDic;

static NSString *favoratePath;
static NSString *rotatePath;

@implementation TCAirportModel

#pragma mark interface method

+(NSString *)getAirportICAO
{
	return airportICAO;
}

//返回所有机场列表
+(NSArray*)getAirportArray
{
	return airportArray;
}

//返回任务机场列表
+(NSArray*)getTaskAirportArray
{
    taskAirportArray = [[NSMutableArray alloc] init];
    
    NSString *taskDeparture = [[ChartContext instance] objectForKey:CTX_TASK_DEPARTURE];
    if (taskDeparture.length>0) {
        NSString *name = [self getAirportNameByICAO:taskDeparture];
        if (name.length >0) {
            NSDictionary *dic = [[[NSDictionary alloc]initWithObjectsAndKeys:taskDeparture,@"icao", name,@"name", nil]autorelease];
            [taskAirportArray addObject:dic];
        }
    }
    
    NSString *taskArrival = [[ChartContext instance] objectForKey:CTX_TASK_ARRIVAL];
    if (taskArrival.length>0) {
        NSString *name = [self getAirportNameByICAO:taskArrival];
        if (name.length >0) {
            NSDictionary *dic2 =[[[NSDictionary alloc]initWithObjectsAndKeys:taskArrival,@"icao", name,@"name", nil]autorelease];
            [taskAirportArray addObject:dic2];
        }
    }
    
    NSString *taskAlternates = [[ChartContext instance] objectForKey:CTX_TASK_ALTERNATES];
    NSArray *alternateArr = [taskAlternates componentsSeparatedByString:@","];
    for (NSString *airport in alternateArr) {
        if (airport.length>0) {
            NSString *name = [self getAirportNameByICAO:airport];
            if (name.length >0) {
                NSDictionary *dic3 =[[[NSDictionary alloc]initWithObjectsAndKeys:airport,@"icao", name,@"name", nil]autorelease];
                [taskAirportArray addObject:dic3];
            }
        }
    }
    
	return taskAirportArray;
}

+ (NSString *)getAirportNameByICAO:(NSString *)icao
{
    NSString *name = nil;
    for (NSDictionary *dic in airportArray) {
        if ([icao isEqualToString:dic[@"icao"]]) {
            name = dic[@"name"];
            break;
        }
    }
    return name;
}

//返回机场包含的所有分类（REF等）
+(NSArray*)getTypes:(NSString*)icao
{
	airportICAO = icao;
	for (NSDictionary *dic in airportArray)
	{
		if([[dic objectForKey:@"icao"] isEqualToString:icao])
		{
			return [dic objectForKey:@"typesArray"];
		}
	}
	return nil;
}

//返回REF 等分类下的所有子分类列表
+(NSArray*)getSubTypes:(NSString*)type
{
	if(![type isEqualToString:@""])
	{
		typeName = type;
	}
	NSArray *typesArray = [TCAirportModel getTypes:airportICAO];
	for(NSDictionary *typeDic in typesArray)
	{
		if ([[typeDic objectForKey:@"typeName"] isEqualToString:typeName])
		{
			return [typeDic objectForKey:@"subTypesArray"];
		}
	}
	return nil;
}

+ (NSString *)getType
{
    return typeName;
}

+ (void)setTypeName:(NSString *)newType
{
    typeName = [newType copy];
}

+(NSMutableDictionary *)getFavorateDic
{
	return favorateDic;
}

+(void)setFavorateDic:(NSDictionary *)dic value:(NSString *)value
{
//	[favorateDic setValue:value forKey:key];
    NSString *uuid = [[ChartContext instance] objectForKey:CHART_GETID];
    NSString *user = [[ChartContext instance] objectForKey:kContextUser];
    NSString *file = [[ChartFileHelper pathForChartsPlist:uuid userName:user] stringByAppendingPathComponent:@"/favorate2.plist"];
    
    NSMutableDictionary *airPortDic =  [NSMutableDictionary dictionaryWithDictionary:favorateDic[airportICAO]];
    NSMutableArray *typeArray =  [NSMutableArray arrayWithArray:airPortDic[typeName]];
    if ([value isEqualToString:@"YES"]) {
        [typeArray addObject:dic];
    }
    else {
        [typeArray removeObject:dic];
    }
    
    [airPortDic setObject:typeArray forKey:typeName];
    if ([typeArray count] == 0) {
        [airPortDic removeObjectForKey:typeName];
    }
    
    [favorateDic setObject:airPortDic forKey:airportICAO];
    if ([airPortDic count] == 0) {
        [favorateDic  removeObjectForKey:airportICAO];
    }
    
    [favorateDic writeToFile:file atomically:YES];
}

+ (void)changedFavoriteDic:(NSDictionary *)dic key:(NSString *)key status:(NSString *)status
{
    NSString *uuid = [[ChartContext instance] objectForKey:CHART_GETID];
    NSString *user = [[ChartContext instance] objectForKey:kContextUser];
    NSString *file = [[ChartFileHelper pathForChartsPlist:uuid userName:user] stringByAppendingPathComponent:@"/favorate2.plist"];
    
    NSMutableDictionary *airPortDic =  [NSMutableDictionary dictionaryWithDictionary:favorateDic[airportICAO]];
    NSMutableArray *typeArray =  [NSMutableArray arrayWithArray:airPortDic[key]];
    if ([status isEqualToString:@"YES"]) {
        [typeArray addObject:dic];
    }
    else {
        [typeArray removeObject:dic];
    }
    
    [airPortDic setObject:typeArray forKey:key];
    if ([typeArray count] == 0) {
        [airPortDic removeObjectForKey:key];
    }
    
    [favorateDic setObject:airPortDic forKey:airportICAO];
    if ([airPortDic count] == 0) {
        [favorateDic  removeObjectForKey:airportICAO];
    }
    
    [favorateDic writeToFile:file atomically:YES];
}

+(NSMutableDictionary *)getRotateDic
{
	return rotateDic;
}

+(void)setRotateDic:(NSString *)key value:(NSString *)value
{
	if (!rotateDic) {
		rotateDic = [[NSMutableDictionary alloc] init];
	}
	[rotateDic setValue:value forKey:key];
    
    NSString *uuid = [[ChartContext instance] objectForKey:CHART_GETID];
    NSString *user = [[ChartContext instance] objectForKey:kContextUser];
	[rotateDic writeToFile:[[ChartFileHelper pathForChartsPlist:uuid userName:user] stringByAppendingPathComponent:@"/rotate.plist"] atomically:YES];
}

+(NSMutableDictionary *)getSelectedDic
{
	return selectedDic;
}

+(void)setSelectedDic:(NSMutableDictionary *)value
{
	NSString *key = [airportICAO stringByAppendingString:typeName];
	if (!selectedDic) {
		selectedDic = [[NSMutableDictionary alloc]init];
	}
	[selectedDic setValue:value forKey:key];
}

+(void)removeSelectedDicAndAirportICAO
{
    if (selectedDic) {
        [selectedDic removeAllObjects];
    }
    if (airportICAO) {
        airportICAO = nil;
    }
}

#pragma ---

+(void)loadAirportFromDB:(NSString*)dbPath uuid:(NSString*)uuid
{
//    NIF_TRACE(@"path=%@--uuid=%@",dbPath,uuid);
    
    NSMutableArray *airportMutableArray = [[[NSMutableArray alloc] init]autorelease];
	NSMutableDictionary *airportMutableDic = [[[NSMutableDictionary alloc] init] autorelease];
	
    [[ChartContext instance] setValue:uuid forKey:CHART_GETID];
    NSString *user = [[ChartContext instance] objectForKey:kContextUser];

	favoratePath = [[ChartFileHelper pathForChartsPlist:uuid userName:user]  stringByAppendingPathComponent:@"favorate2.plist"];
	BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:favoratePath];
	if(exists)
	{
		favorateDic = [[NSMutableDictionary alloc] initWithContentsOfFile:favoratePath];
	}
	else
	{
		favorateDic = [[NSMutableDictionary alloc] init];
        [favorateDic writeToFile:favoratePath atomically:YES];

	}
	
	rotatePath = [[ChartFileHelper pathForChartsPlist:uuid userName:@""]  stringByAppendingPathComponent:@"rotate.plist"];
	exists = [[NSFileManager defaultManager] fileExistsAtPath:rotatePath];
	if(exists)
	{
		rotateDic = [[NSMutableDictionary alloc] initWithContentsOfFile:rotatePath];
	}
	else
	{
		rotateDic = [[NSMutableDictionary alloc] init];
	}
	NSString *airportPath = [[ChartFileHelper pathForChartsPlist:uuid userName:@""] stringByAppendingPathComponent:@"/airport.plist"];
	exists = [[NSFileManager defaultManager] fileExistsAtPath:airportPath];
	if(exists){
	
        NSArray*arr=[[NSArray alloc] initWithContentsOfFile:airportPath];
		airportArray = arr;
	}
	else
	{
        FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
        
        bool ret = [db openWithFlags:SQLITE_OPEN_READONLY];
        if (!ret) {
            NSLog(@"航图数据不存在！");
            return;
        }
        
        NSString *sql = [NSString stringWithFormat:@"select * from %@ order by icao", AIRPORTTABLE];
		FMResultSet *results = [db executeQuery:sql];

		while( [results next] )
		{
			[airportMutableDic setValue:[results objectForColumnName:@"name"] forKey:@"name"];
			[airportMutableDic setValue:[results objectForColumnName:@"icao"] forKey:@"icao"];
            NSMutableArray *array = [self getTypesArray:[results objectForColumnName:@"id"] database:db airportICAO:[results objectForColumnName:@"icao"]];
            NSMutableDictionary *dictonary = [self getSubtypeDic1:[results objectForColumnName:@"id"] database:db];
            if (dictonary.count > 0) {
                [array addObject:dictonary];
            }
			[airportMutableDic setValue:array forKey:@"typesArray"];
			[airportMutableArray addObject:[NSDictionary dictionaryWithDictionary:airportMutableDic]];
		}
		[self addAirportInfo:db airportMutableArray:airportMutableArray];
		if (airportArray) {
			[airportArray release];
		}
		airportArray = [[NSArray alloc]initWithArray:airportMutableArray];
		[airportArray writeToFile:airportPath atomically:YES];
		[db close];
	}
}

+(NSMutableArray*)getTypesArray:(NSString*)airportID database:(FMDatabase*)db airportICAO:(NSString *)icao
{
	NSString *sql = [NSString stringWithFormat:@"SELECT distinct chart_code from %@ WHERE airport_id=%@",CHARTTABLE,airportID];
	FMResultSet *results = [db executeQuery:sql];
	NSMutableArray *typesArray = [[[NSMutableArray alloc] init] autorelease];
	while( [results next] )
    {
		[typesArray addObject:[self getTypeDic:airportID chartType:[results objectForColumnName:@"chart_code"] database:db airportICAO:icao] ];
	}
	return typesArray;
}
	
+(NSMutableDictionary*)getTypeDic:(NSString*)airportID chartType:(NSString*)chartType database:(FMDatabase*)db airportICAO:(NSString *)icao
{
	NSMutableDictionary *typeDic = [[[NSMutableDictionary alloc]init]autorelease];
	[typeDic setValue:chartType forKey:@"typeName"];
	
	NSString *sql = [NSString stringWithFormat:@"SELECT distinct chart_type from %@ a left outer join %@ b on a.type_id=b.id where airport_id=%@ and chart_code='%@' order by b.display_order",CHARTTABLE,CHARTTYPETABLE,airportID,chartType];
	
	FMResultSet *results = [db executeQuery:sql];
	
	NSMutableArray *subTypesArray = [[[NSMutableArray alloc] init]autorelease];
    while( [results next] )
    {
        if (![[results objectForColumnName:@"chart_type"] isEqualToString:@"补充资料"]) {
        
//        }else{
            [subTypesArray addObject:[self getSubtypeDic:airportID chartType:chartType chartSubtype:[results objectForColumnName:@"chart_type"] database:db]];
        }
	}
	
	[typeDic setValue:subTypesArray forKey:@"subTypesArray"];
	return typeDic;
}

+(NSMutableDictionary *)getSubtypeDic:(NSString*)airportID chartType:(NSString*)chartType chartSubtype:(NSString*)chartSubtype database:(FMDatabase*)db
{
	NSString *sql = [NSString stringWithFormat:@"SELECT name,file_name,page,is_modified FROM %@ where airport_id=%@ and chart_code='%@' and chart_type='%@' order by page",CHARTTABLE,airportID,chartType,chartSubtype];

	FMResultSet *results = [db executeQuery:sql];
	
	NSMutableDictionary *subTypeDic = [[[NSMutableDictionary alloc]init]autorelease];
	NSMutableArray *chartsArray = [[[NSMutableArray alloc] init] autorelease];
	[subTypeDic setObject:chartSubtype forKey:@"subTypeName"];
    
	while( [results next] )
    {
		NSMutableDictionary *chartDic = [[[NSMutableDictionary alloc] init] autorelease];
		[chartDic setValue:[results objectForColumnName:@"name"] forKey:@"name"];
		[chartDic setValue:[results objectForColumnName:@"file_name"] forKey:@"file_name"];
		[chartDic setValue:[results objectForColumnName:@"page"] forKey:@"page"];
		[chartDic setValue:[results objectForColumnName:@"is_modified"] forKey:@"is_modified"];
        if ([chartSubtype isEqualToString:@"补充资料"]) {
            [chartDic setValue:@"NO" forKey:@"isChart"];
        }else{
            [chartDic setValue:@"YES" forKey:@"isChart"];
        }
		[chartsArray addObject:chartDic];
	}
	
	
	[subTypeDic setObject:chartsArray forKey:@"chartsArray"];
	
	return subTypeDic;
}

+(NSMutableDictionary *)getSubtypeDic1:(NSString*)airportID database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:@"SELECT a.id,a.name,a.file_name,a.page,a.is_modified,b.type,b.display_order FROM %@ a left outer join %@ b on a.type_id = b.id where airport_id='%@' and display_order='1'",CHARTTABLE,CHARTTYPETABLE,airportID];
    NSMutableDictionary *typeDic = [[[NSMutableDictionary alloc]init] autorelease];

	FMResultSet *results = [db executeQuery:sql];

	while( [results next] )
    {
        [typeDic setValue:@"黄页" forKey:@"typeName"];
        
        NSMutableArray *subTypesArray = [[[NSMutableArray alloc]init] autorelease];
        NSMutableDictionary *subTypeDic = [[[NSMutableDictionary alloc]init] autorelease];
        
        [subTypeDic setValue:@"补充资料" forKey:@"subTypeName"];
        
        NSMutableArray *chartsArray = [[[NSMutableArray alloc]init] autorelease];
        NSMutableDictionary *chartDic = [[[NSMutableDictionary alloc]init] autorelease];
      
		[chartDic setValue:[results objectForColumnName:@"file_name"] forKey:@"file_name"];
		[chartDic setValue:[results objectForColumnName:@"page"] forKey:@"page"];
        [chartDic setValue:[results objectForColumnName:@"is_modified"] forKey:@"is_modified"];
		[chartDic setValue:[results objectForColumnName:@"name"] forKey:@"name"];
        [chartDic setValue:@"NO" forKey:@"isChart"];
        
        [chartsArray addObject:chartDic];
        
        [subTypeDic setValue:chartsArray forKey:@"chartsArray"];
        
        [subTypesArray addObject:subTypeDic];
        [typeDic setValue:subTypesArray forKey:@"subTypesArray"];
    }
	
	return typeDic;
}

+(void)addAirportInfo:(FMDatabase *)db airportMutableArray:(NSMutableArray *)airportMutableArray
{
	for (NSMutableDictionary *airportDic in airportMutableArray)
	{
		NSString *icao = [airportDic objectForKey:@"icao"];
		NSString *sql = [NSString stringWithFormat:@"SELECT a.file_name,a.is_modified,b.icao FROM %@ a left outer join %@ b on a.airport_id=b.id where b.icao='%@'",DOCTABLE,AIRPORTTABLE,icao];
        
		FMResultSet *results = [db executeQuery:sql];
		if ([results next])
		{
			bool hasREF = false;
//			for (NSMutableDictionary *typeDic in [airportDic objectForKey:@"typesArray"])
//			{
//
//				if ([[typeDic objectForKey:@"typeName"] isEqualToString:@"REF"])
//				{
//					NSMutableDictionary *subTypeDic = [[[NSMutableDictionary alloc]init] autorelease];
//					
//					[subTypeDic setValue:@"机场细则" forKey:@"subTypeName"];
//					NSMutableArray *chartsArray = [[[NSMutableArray alloc]init] autorelease];
//					NSMutableDictionary *chartDic = [[[NSMutableDictionary alloc]init] autorelease];
//					NSString *fileName = [results objectForColumnName:@"file_name"];
//					NSString *name = [fileName substringToIndex:fileName.length-4];
//					[chartDic setValue:fileName forKey:@"file_name"];
//					[chartDic setValue:icao forKey:@"page"];
//					[chartDic setValue:[results objectForColumnName:@"is_modified"] forKey:@"is_modified"];
//					[chartDic setValue:name forKey:@"name"];
//					[chartDic setValue:@"NO" forKey:@"isChart"];
//					
//					[chartsArray addObject:chartDic];
//					
//					[subTypeDic setValue:chartsArray forKey:@"chartsArray"];
//					NSMutableArray *subTypesArray = [typeDic objectForKey:@"subTypesArray"];
//					[subTypesArray insertObject:subTypeDic atIndex:0];
//					
//					hasREF = true;
//				}
//
//			}
			if (!hasREF)
			{
				NSMutableDictionary *typeDic = [[[NSMutableDictionary alloc]init] autorelease];
				[typeDic setValue:@"细则" forKey:@"typeName"];
				
				NSMutableArray *subTypesArray = [[[NSMutableArray alloc]init] autorelease];
				
				NSMutableDictionary *subTypeDic = [[[NSMutableDictionary alloc]init] autorelease];
				
				[subTypeDic setValue:@"机场细则" forKey:@"subTypeName"];
				
				NSMutableArray *chartsArray = [[[NSMutableArray alloc]init] autorelease];
				NSMutableDictionary *chartDic = [[[NSMutableDictionary alloc]init] autorelease];
				
				NSString *fileName = [results objectForColumnName:@"file_name"];
				NSString *name = [fileName substringToIndex:fileName.length-4];
				[chartDic setValue:fileName forKey:@"file_name"];
				[chartDic setValue:icao forKey:@"page"];
				[chartDic setValue:[results objectForColumnName:@"is_modified"] forKey:@"is_modified"];
				[chartDic setValue:name forKey:@"name"];
				[chartDic setValue:@"NO" forKey:@"isChart"];
				
				[chartsArray addObject:chartDic];
				
				[subTypeDic setValue:chartsArray forKey:@"chartsArray"];
				
				[subTypesArray addObject:subTypeDic];
				[typeDic setValue:subTypesArray forKey:@"subTypesArray"];
                
				NSMutableArray *typesArray = [airportDic objectForKey:@"typesArray"];
                [typesArray addObject:typeDic];
//				[typesArray insertObject:typeDic atIndex:0];
								
			}
		}

	}
}






@end
